<template>
  <div class="team-collaboration-detail">
    <!-- 页面头部 -->
    <el-page-header @back="$router.go(-1)" title="四员协同详情" />

    <!-- 月度统计概览 -->
    <div class="monthly-overview">
      <el-card>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number target">{{ monthlyStats.target }}</div>
              <div class="stat-label">月度目标</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number completed">{{ monthlyStats.completed }}</div>
              <div class="stat-label">已提交</div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="stat-item">
              <div class="stat-number remaining">{{ monthlyStats.remaining }}</div>
              <div class="stat-label">待提交</div>
            </div>
          </el-col>
        </el-row>

        <!-- 进度条 -->
        <div class="progress-section">
          <div class="progress-info">
            <span>本月完成进度</span>
            <span>{{ completionRate }}%</span>
          </div>
          <el-progress :percentage="completionRate" :color="progressColor" />
        </div>

        <!-- 截止时间提醒 -->
        <div class="deadline-reminder">
          <el-alert
            :title="deadlineText"
            type="warning"
            :closable="false"
            show-icon
          />
        </div>
      </el-card>
    </div>

    <!-- 月份选择 -->
    <div class="month-selector">
      <el-card>
        <el-button @click="showMonthPicker = true" type="text">
          <el-icon><Calendar /></el-icon>
          选择月份: {{ selectedMonth }}
        </el-button>
      </el-card>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter">
      <el-card>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索协同内容或客户名称"
          clearable
          @input="handleSearch"
          @clear="handleClear"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="filter-tabs">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane label="已提交" name="submitted" />
            <el-tab-pane label="草稿" name="draft" />
          </el-tabs>
        </div>
      </el-card>
    </div>

    <!-- 协同记录列表 -->
    <div class="collaboration-list">
      <el-card>
        <div v-loading="loading">
          <div v-for="record in filteredRecords" :key="record.id" class="record-item">
            <el-card class="record-card" shadow="hover" @click="viewRecordDetail(record)">
              <div class="record-header">
                <div class="record-title">
                  <h4>{{ record.title }}</h4>
                  <el-tag
                    :type="record.status === 'submitted' ? 'success' : 'warning'"
                    size="small"
                  >
                    {{ record.status === 'submitted' ? '已提交' : '草稿' }}
                  </el-tag>
                </div>
                <div class="record-meta">
                  <span class="client-name">{{ record.clientName }}</span>
                  <span class="collaboration-type">{{ record.collaborationType }}</span>
                </div>
              </div>

              <div class="record-content">
                <p class="record-description">{{ record.description }}</p>
                <div class="record-info">
                  <span class="submit-time">
                    <el-icon><Clock /></el-icon>
                    {{ record.submitTime || '未提交' }}
                  </span>
                </div>
              </div>

              <div class="record-actions" @click.stop>
                <el-button
                  type="default"
                  size="small"
                  @click="viewRecord(record)"
                >
                  查看
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="deleteRecord(record)"
                >
                  删除
                </el-button>
              </div>
            </el-card>
          </div>

          <div v-if="!finished" class="load-more">
            <el-button @click="onLoad" :loading="loading">加载更多</el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 记录详情弹窗 -->
    <el-dialog v-model="showRecordDetail" title="协同记录详情" width="90%">
      <div v-if="selectedRecord">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="协同标题">{{ selectedRecord.title }}</el-descriptions-item>
          <el-descriptions-item label="涉及客户">{{ selectedRecord.clientName }}</el-descriptions-item>
          <el-descriptions-item label="客户代码">{{ selectedRecord.clientCode }}</el-descriptions-item>
          <el-descriptions-item label="协同类型">{{ selectedRecord.collaborationType }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="selectedRecord.status === 'submitted' ? 'success' : 'warning'">
              {{ selectedRecord.status === 'submitted' ? '已提交' : '草稿' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item
            v-if="selectedRecord.status === 'submitted'"
            label="提交时间"
          >
            {{ selectedRecord.submitTime }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="record-content">
          <h4>协同内容</h4>
          <el-card class="content-card">
            <p class="content-text">{{ selectedRecord.content }}</p>
          </el-card>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showRecordDetail = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 月份选择器 -->
    <el-dialog v-model="showMonthPicker" title="选择月份" width="300px">
      <el-date-picker
        v-model="selectedDateValue"
        type="month"
        placeholder="选择月份"
        format="YYYY年MM月"
        value-format="YYYY-MM"
        @change="confirmMonth"
      />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMonthPicker = false">取消</el-button>
          <el-button type="primary" @click="confirmMonth">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 浮动操作按钮 -->
    <div class="fab-container">
      <el-button
        type="primary"
        circle
        @click="createNewRecord"
      >
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Calendar, Clock, Plus } from '@element-plus/icons-vue'
import { trpc } from '@/utils/trpc'
import { AuthUtils } from '@/utils/auth'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const activeTab = ref('all')
const loading = ref(false)
const finished = ref(false)
const showRecordDetail = ref(false)
const showMonthPicker = ref(false)
const selectedRecord = ref(null)
// 初始化为当前月份
const now = new Date()
const currentYear = now.getFullYear()
const currentMonth = now.getMonth() + 1
const selectedMonth = ref(`${currentYear}年${currentMonth.toString().padStart(2, '0')}月`)
const selectedDateValue = ref(`${currentYear}-${currentMonth.toString().padStart(2, '0')}`)

// 月度统计数据
const monthlyStats = reactive({
  target: 1,
  completed: 0,
  remaining: 1
})

// 协同记录数据
const collaborationRecords = ref([])
const teamService = ref(null)

// 计算属性
const completionRate = computed(() => {
  return Math.round((monthlyStats.completed / monthlyStats.target) * 100)
})

const progressColor = computed(() => {
  const rate = completionRate.value
  if (rate >= 80) return '#07c160'
  if (rate >= 60) return '#ff976a'
  return '#ff6b6b'
})

const deadlineText = computed(() => {
  const remaining = monthlyStats.remaining
  if (remaining === 0) {
    return '本月任务已完成！'
  }
  return `本月还需提交 ${remaining} 条协同记录，请及时完成`
})

const filteredRecords = computed(() => {
  let filtered = collaborationRecords.value

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(record =>
      record.title.includes(searchKeyword.value) ||
      record.clientName.includes(searchKeyword.value) ||
      record.content.includes(searchKeyword.value)
    )
  }

  // 根据状态标签过滤
  if (activeTab.value !== 'all') {
    filtered = filtered.filter(record => record.status === activeTab.value)
  }

  return filtered
})

// 方法
const handleSearch = () => {
  ElMessage.success(`搜索: ${searchKeyword.value}`)
}

const handleClear = () => {
  searchKeyword.value = ''
}

const handleTabChange = (name) => {
  activeTab.value = name
}

const onLoad = async () => {
  try {
    loading.value = true
    await new Promise(resolve => setTimeout(resolve, 1000))
    finished.value = true
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

const viewRecordDetail = (record) => {
  selectedRecord.value = record
  showRecordDetail.value = true
}

const editRecord = (record) => {
  ElMessage.success(`编辑协同记录: ${record.title}`)
  showRecordDetail.value = false
  // 跳转到编辑页面
  // router.push(`/team-collaboration/edit/${record.id}`)
}

const submitRecord = async (record) => {
  try {
    await ElMessageBox.confirm(
      '确定要提交这条协同记录吗？提交后将无法修改。',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟提交
    record.status = 'submitted'
    record.submitTime = new Date().toLocaleString()
    monthlyStats.completed++
    monthlyStats.remaining--

    ElMessage.success('提交成功')
    showRecordDetail.value = false
  } catch (error) {
    // 用户取消
  }
}

const viewRecord = (record) => {
  viewRecordDetail(record)
}

const deleteRecord = async (record) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条协同记录吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 调用API删除记录
    const result = await trpc.workLog.delete.mutate({
      id: record.id.toString(),
      managerId
    })

    if (result.success) {
      // 更新本地数据
      const index = collaborationRecords.value.findIndex(r => r.id === record.id)
      if (index > -1) {
        collaborationRecords.value.splice(index, 1)
        monthlyStats.completed--
        monthlyStats.remaining = Math.max(0, monthlyStats.target - monthlyStats.completed)
      }
      ElMessage.success('删除成功')
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('删除记录失败:', error)
    if (error.message !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const confirmMonth = () => {
  if (selectedDateValue.value) {
    const [year, month] = selectedDateValue.value.split('-')
    selectedMonth.value = `${year}年${month}月`
    showMonthPicker.value = false
    loadData() // 重新加载该月份的数据
  }
}

const createNewRecord = () => {
  // 跳转到四员协同主页面，并传递参数以自动打开添加对话框
  router.push({
    name: 'TeamCollaboration',
    query: { action: 'add' }
  })
}

const loadData = async () => {
  try {
    loading.value = true
    const managerId = getCurrentManagerId()
    if (!managerId) return

    // 获取四员协同服务
    const serviceList = await trpc.service.list.query({ pageSize: 100 })
    if (!serviceList?.success) throw new Error('加载服务列表失败')
    const services = serviceList.data.data || serviceList.data || []
    const foundService = services.find((s) => s.serviceName?.includes('四员协同'))
    
    if (!foundService) {
      console.warn('未找到四员协同服务')
      return
    }
    
    teamService.value = foundService
    
    // 解析选择的月份
    const [year, month] = selectedDateValue.value.split('-')
    const startDate = new Date(parseInt(year), parseInt(month) - 1, 1)
    const endDate = new Date(parseInt(year), parseInt(month), 0)
    
    // 获取该月的工作记录统计
    const result = await trpc.workLog.serviceStats.query({
      managerId,
      serviceId: foundService.id,
      startDate: startDate.toISOString(),
      endDate: endDate.toISOString()
    })

    if (result.success) {
      const recentLogs = result.data.recentLogs || []
      
      // 更新统计数据
      monthlyStats.target = foundService.cycleValue || 1
      monthlyStats.completed = recentLogs.length
      monthlyStats.remaining = Math.max(0, monthlyStats.target - monthlyStats.completed)
      
      // 转换数据格式以适应详情界面
      collaborationRecords.value = recentLogs.map((log, index) => ({
        id: log.id,
        title: `四员协同工作记录 ${index + 1}`,
        description: log.notes || '暂无详细记录',
        clientName: log.client?.clientName || '系统记录',
        clientCode: log.client?.clientCode || '000000000000',
        collaborationType: '四员协同',
        status: 'submitted',
        submitTime: new Date(log.completionDate).toLocaleString(),
        content: log.notes || '暂无详细记录'
      }))
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const getCurrentManagerId = () => {
  const user = AuthUtils.getUser()
  return user?.id || null
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.team-collaboration-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
  padding-bottom: 80px;
}

.monthly-overview {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-number.target {
  color: #333;
}

.stat-number.completed {
  color: #67c23a;
}

.stat-number.remaining {
  color: #e6a23c;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.progress-section {
  margin-top: 30px;
  padding: 0 20px;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
}

.deadline-reminder {
  margin-top: 20px;
  padding: 0 20px;
}

.month-selector {
  margin-bottom: 20px;
}

.search-filter {
  margin-bottom: 20px;
}

.filter-tabs {
  margin-top: 15px;
}

.collaboration-list {
  margin-bottom: 20px;
}

.record-item {
  margin-bottom: 15px;
}

.record-card {
  cursor: pointer;
  transition: all 0.3s;
}

.record-card:hover {
  transform: translateY(-2px);
}

.record-header {
  margin-bottom: 15px;
}

.record-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-title h4 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.record-meta {
  display: flex;
  gap: 15px;
  font-size: 14px;
  color: #666;
}

.client-name {
  font-weight: bold;
  color: #333;
}

.collaboration-type {
  color: #409eff;
}

.record-content {
  margin-bottom: 15px;
}

.record-description {
  margin: 0 0 10px 0;
  color: #666;
  line-height: 1.5;
}

.record-info {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.submit-time {
  display: flex;
  align-items: center;
  gap: 4px;
}

.record-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.record-content h4 {
  margin: 20px 0 15px 0;
  font-size: 16px;
  font-weight: bold;
}

.content-card {
  margin-top: 10px;
}

.content-text {
  line-height: 1.6;
  font-size: 14px;
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.fab-container {
  position: fixed;
  bottom: 30px;
  right: 30px;
  z-index: 999;
}

.fab-container .el-button {
  width: 56px;
  height: 56px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
